package org.pada.client.dto;

import java.util.*;
import java.util.function.Function;

/**
 * @author pengshen
 * @date 2023.12.29 18:02
 */
public class PageResp<T> extends Resp {


    private static final long serialVersionUID = 1L;

    private int totalCount = 0;

    private int pageSize = 1;

    private int pageIndex = 1;

    private Collection<T> data;

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPageSize() {
        if (pageSize < 1) {
            return 1;
        }
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        if (pageSize < 1) {
            this.pageSize = 1;
        } else {
            this.pageSize = pageSize;
        }
    }

    public int getPageIndex() {
        if (pageIndex < 1) {
            return 1;
        }
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        if (pageIndex < 1) {
            this.pageIndex = 1;
        } else {
            this.pageIndex = pageIndex;
        }
    }

    public List<T> getData() {
        return null == data ? Collections.emptyList() : new ArrayList<>(data);
    }

    public void setData(Collection<T> data) {
        this.data = data;
    }

    public int getTotalPages() {
        return this.totalCount % this.pageSize == 0 ? this.totalCount
                / this.pageSize : (this.totalCount / this.pageSize) + 1;
    }

    public boolean isEmpty() {
        return data == null || data.size() == 0;
    }

    public boolean isNotEmpty() {
        return !isEmpty();
    }

    public static PageResp buildSuccess() {
        PageResp resp = new PageResp();
        resp.setSuccess(true);
        return resp;
    }

    public static PageResp buildFailure(String errCode, String errMessage) {
        PageResp resp = new PageResp();
        resp.setSuccess(false);
        resp.setErrCode(errCode);
        resp.setErrMessage(errMessage);
        return resp;
    }

    private static <T> Optional<T> getLast(List<T> data) {
        if (data == null || data.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(data.get(data.size() - 1));
    }

    public static <T> PageResp<T> of(int pageSize, int pageIndex) {
        PageResp<T> resp = new PageResp<>();
        resp.setSuccess(true);
        resp.setData(Collections.emptyList());
        resp.setTotalCount(0);
        resp.setPageSize(pageSize);
        resp.setPageIndex(pageIndex);
        return resp;
    }

    public static <T> PageResp<T> of(Collection<T> data, int totalCount, int pageSize, int pageIndex) {
        PageResp<T> resp = new PageResp<>();
        resp.setSuccess(true);
        resp.setData(data);
        resp.setTotalCount(totalCount);
        resp.setPageSize(pageSize);
        resp.setPageIndex(pageIndex);
        return resp;
    }
}
